<?php
/**
 * OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures
 * all the essential functionalities required for any enterprise.
 * Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com
 *
 * OrangeHRM is free software; you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * OrangeHRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program;
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA
 *
 */
require_once ROOT_PATH . '/lib/confs/Conf.php';
require_once ROOT_PATH . '/lib/confs/sysConf.php';

//require_once ROOT_PATH . '/lib/models/time/AttendanceRecord.php';
//require_once ROOT_PATH . '/lib/extractor/time/EXTRACTOR_AttendanceRecord.php';
require_once ROOT_PATH . '/lib/models/hrfunct/AdministraMana.php';

//require_once ROOT_PATH . '/lib/models/attendance/AttendanceStatistics.php';

class SalaryController {

	private $AttendanceCache;
	private $objTime;
	private $id;
	private $authorizeObj;
	private $db = "";
	private $wilteList = "";
	private $newwiletlist = "";
	private $RuleValue = "";
	private $WeekHolidays = "";

	public function setObjTime($objTime) {
		$this->objTime=$objTime;
	}

	public function getObjTime() {
		return $this->objTime;
	}

	public function setId($id) {
		$this->id=$id;
	}

	public function getId() {
		return $this->id;
	}

	public function __construct() {
		include(ROOT_PATH . '/customConfig/salary.config.php');
		$this->SalaryCache = $_CfgSalary;
		$this->db = new DMLFunctions();
		error_reporting(0);
	}

	public function __distruct() {
		$this->db->dbDisconnect();
	}
	
	//获取薪资配置
	public function getRuleValue($key = "") {
		static $RuleValue = null;
		if ($RuleValue === null) {
			$sql = "select * from hs_hr_sysconfigs where `key`='SalaryRule'";
			$query = $this->db->executeQuery($sql);
			$result = mysql_fetch_array($query, MYSQL_ASSOC);
			if($result['value'] != "") {
				$RuleValue = unserialize($result['value']);
			} else {
				$RuleValue = array();
			}
		}
		
		if($key != "") {
			return $RuleValue[$key];
		} else {
			return $RuleValue;
		}
	}
	/**
	 *薪资规则显示 
	 **/
	public function ShowSalaryRule() {
		$records = $this->getRuleValue();
		//print_r($records);
		//die();
		$path = "/templates/salary/ShowSalaryRule.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}

	/**
	 *薪资规则保存 
	 **/
	public function SaveSalaryRule() {
		
		$value = serialize($_POST);
		//保存数据
		
		$sql = "select * from hs_hr_sysconfigs where `key`='SalaryRule'";
		$query = $this->db->executeQuery($sql);
		$records = mysql_fetch_array($query, MYSQL_ASSOC);
		if($records == "") {
			$sql = "insert into hs_hr_sysconfigs (`key`,`value`,`addtime`) values ('SalaryRule','{$value}',".time().")";
			$resulq = $this->db->executeQuery($sql);
		} else {
			$sql = "update hs_hr_sysconfigs set `value` = '{$value}' where `key`='SalaryRule'";
			$resulq = $this->db->executeQuery($sql);
		}
		$this->redirect("保存成功", "?salcode=salaryrule");
	}
	
	/**
	 *员工工资档案 
	 **/
	public function showBasicSalaryList() {
		$where = "Where 1=1 ";
		$year = isset($_POST['year']) ? intval($_POST['year']) : @date("Y",time());
		$month = isset($_POST['month']) ? intval($_POST['month']) : @date("n",time());
		$where .= " and year={$year} and month={$month}";
		$sysConst = new sysConf();
		$where .= $this->GetSearchSlqWhere();
        $limit = "";
        $list = array();
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;

            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }
        
		$sql = "select count(*) as allcount from hs_hr_salary_basic a {$where}";
		$query = $this->db->executeQuery($sql);
		$Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
		
		$sql = "select a.*, b.jobtit_name, b.jobtit_salary from hs_hr_salary_basic a left join hs_hr_job_title b on a.job_code=b.jobtit_code {$where} {$limit}";
		//echo $sql;exit;
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$list[] = $row;
		}
		//print_r($list);
		//die();
		$records['list'] = $list;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $Allcount['allcount'];
		$path = "/templates/salary/basicSalaryList.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}

	/**
	 * 生成某月份的员工工资档案
	 * @author johnson  2012/05/13
	 */
	public function generateBasicSalaryList() {

		if ($_SESSION['isAdmin'] == 'No') {
// 			die('You are not authorized to view this page');
		}

		//$path = "/templates/salary/basicSalaryList.php";
		
		$year = isset($_POST['year']) ? intval($_POST['year']) : @date("Y",time());
		$month = isset($_POST['month']) ? intval($_POST['month']) : @date("n",time());

		$basicsql = "select a.emp_number as mbid, a.emp_firstname, a.job_title_code, b.* from hs_hr_employee a left join hs_hr_emp_basicsalary b on a.emp_number=b.emp_number where a.emp_status!='EST000' order by a.emp_number asc";
		$basicquery = $this->db->executeQuery($basicsql);
		while ($row = mysql_fetch_array($basicquery, MYSQL_ASSOC)) {
			$mbid = $row['mbid'];
			$name = $row['emp_firstname'];
			$job_code = $row['job_title_code'];
			$salary = $row['ebsal_basic_salary'] ? $row['ebsal_basic_salary'] : 0;
			$sql = "select id from hs_hr_salary_basic where year='$year' and month='$month' and emp_number='$mbid'";
			$query = $this->db->executeQuery($sql);
			$info = mysql_fetch_row($query);
			if(!$info[0]) {
				$exesql = "insert into hs_hr_salary_basic(emp_number,emp_name,year,month,job_code,hight_temp_allowance,night_work_allowance,other_allowance,losework_insurance,medical_insurance,endowment_insurance,maternity_insurance,housing_fund,other_allowance_remark) values('$mbid','$name','$year','$month','$job_code','".($row['hight_temp_allowance']?$row['hight_temp_allowance']:0)."','".($row['night_work_allowance']?$row['night_work_allowance']:0)."','".($row['other_allowance']?$row['other_allowance']:0)."','".($row['losework_insurance']?$row['losework_insurance']:0)."','".($row['medical_insurance']?$row['medical_insurance']:0)."','".($row['endowment_insurance']?$row['endowment_insurance']:0)."','".($row['maternity_insurance']?$row['maternity_insurance']:0)."','".($row['housing_fund']?$row['housing_fund']:0)."','".$row['other_allowance_remark']."')";
				$this->db->executeQuery($exesql);
				$id = mysql_insert_id();
			}else {
				$id = $info[0];
				$exesql = "update hs_hr_salary_basic set job_code='$job_code',hight_temp_allowance='".($row['hight_temp_allowance']?$row['hight_temp_allowance']:0)."',night_work_allowance='".($row['night_work_allowance']?$row['night_work_allowance']:0)."',other_allowance='".($row['other_allowance']?$row['other_allowance']:0)."',losework_insurance='".($row['losework_insurance']?$row['losework_insurance']:0)."',medical_insurance='".($row['medical_insurance']?$row['medical_insurance']:0)."',endowment_insurance='".($row['endowment_insurance']?$row['endowment_insurance']:0)."',maternity_insurance='".($row['maternity_insurance']?$row['maternity_insurance']:0)."',housing_fund='".($row['housing_fund']?$row['housing_fund']:0)."',other_allowance_remark='".$row['other_allowance_remark']."' where id='$id'";
				$this->db->executeQuery($exesql);
			}
			
			$skillsql = "select a.*, b.skill_allowance_name, b.skill_allowance_salary from hs_hr_emp_skill_allowance as a, hs_hr_skill_allowance as b where a.emp_number='$mbid' and a.skill_alw_id=b.skill_allowance_id";
			$skillquery = $this->db->executeQuery($skillsql);
			$skill_sal = 0;
			$remarks = '';
			while ($skills = mysql_fetch_array($skillquery,MYSQL_ASSOC)) {
				$skill_sal += $skills['skill_allowance_salary']?$skills['skill_allowance_salary']:0;
				$remarks .= $skills['skill_allowance_name']."(津贴".$skills['skill_allowance_salary']."),";
			}
			$remarks = rtrim($remarks,',');
			//$v = serialize($values);
			//$r = serialize($remarks);
			$updsql = "update hs_hr_salary_basic set tec_allowance='$skill_sal',tec_allowance_remark='$remarks' where year='$year' and month='$month' and emp_number='$mbid'";
			$this->db->executeQuery($updsql);
			
			$adminsql = "select b.exam_name, b.exam_salary from hs_hr_emp_admin_exam as a, hs_hr_admin_exam as b where a.emp_number='$mbid' and a.exam_id=b.exam_id";
			$adminquery = $this->db->executeQuery($adminsql);
			$exam_sal = 0;
			$exam_remarks = '';
			while ($admexams = mysql_fetch_array($adminquery,MYSQL_ASSOC)) {
				$exam_sal += $admexams['exam_salary']?$admexams['exam_salary']:0;
				$exam_remarks .= $admexams['exam_name']."(补助".$admexams['exam_salary']."),";
			}
			$exam_remarks = rtrim($exam_remarks,',');
			$updsql = "update hs_hr_salary_basic set adm_exam_salary='$exam_sal',adm_exam_remarks='$exam_remarks' where year='$year' and month='$month' and emp_number='$mbid'";
			$this->db->executeQuery($updsql);
		}
		
		//$records['list'] = $list;
		//$records['year'] = $year;
		//$records['month'] = $month;
		//$records['rights'] = $_SESSION['localRights'];

		//$template = new TemplateMerger($records, $path);
		//$template->display();
		//$this->showBasicSalaryList();
	}

	/**
	 *获取迟到早退矿工 
	 **/
	public function GetZaoTuiKuang($row,$StartWorkTime,$EndWorkTime,$Rule) {
		if(($row['starttime'] - $StartWorkTime >= intval($Rule['yunXuLate']*60)) &&  ($row['starttime'] - $StartWorkTime <= intval($Rule['moreYunXuLate']*60))) {
			$row['later'] = 1;
			$row['beizhu'] = "迟到";
		//判断矿工
		} elseif($row['starttime'] - $StartWorkTime > intval($Rule['moreYunXuLate']*60)) {
			$row['LkuangGong'] = 1;
			$row['beizhu'] = "矿工";
		}
		//判断早退
		if(($EndWorkTime - $row['endtime'] >= intval($Rule['zaoTuiMinTime']*60)) && ($EndWorkTime - $row['endtime'] <= intval($Rule['moreZaoTuiMinTime']*60))) {
			$row['ZaoTui'] = 1;
			if($row['LkuangGong'] != 1) {
				if($row['later'] == 1) {
					$row['beizhu'] = "迟到 - 早退";
				} else {
					$row['beizhu'] = "早退";
				}
			}
		//判断矿工
		} elseif($EndWorkTime - $row['endtime'] > intval($Rule['moreZaoTuiMinTime']*60)) {
			$row['ZkuangGong'] = 1;
			$row['beizhu'] = "矿工";
		}
		return $row;
	}

	/**
	 *获取搜索的sqlwhere 
	 **/
	function GetSearchSlqWhere($year="",$month="",$code="",$name="",$type="") {
		$where = "";
		$loc_code = isset($_POST['loc_code'])?htmlspecialchars(trim($_POST['loc_code'])):"";
		$loc_name = isset($_POST['loc_name'])?htmlspecialchars(trim($_POST['loc_name'])):"";
		if($code != "") $loc_code = $code;
		if($name != "") $loc_name = $name;
		if($loc_name != "") {
			if($loc_name == "emp_firstname") {
				$where .= " and emp_name like '%{$loc_name}%' ";
			} elseif($loc_name == "title") {
				$where .= " and department like '%{$loc_name}%' ";
			} else {
				$where .= " and {$loc_code} = '{$loc_name}' ";
			}
		}
		if($type!="CalSalary") {
			if($year != "") {
				$where .= " and year = '{$year}' ";
			}
			if($month != "") {
				$where .= " and month = '{$month}' ";
			}
		}
		return $where;
	}
	
	/**
	 *获取员工名字和id
	 **/
	public function GetEmpName() {
		
		$EmpName = $_POST['EmpName'];
		$tbname = $_POST['tbname'];
		$EmpNameId = $_POST['EmpNameId'];
		$div = $_POST['div'];
		$EmpIdId = $_POST['EmpIdId'];
		$sql = "select * from  hs_hr_employee  where emp_firstname like '%{$EmpName}%'";
		//echo $sql;
		//die();
		$query = $this->db->executeQuery($sql);
		
		$str ='<tr style="cursor:default" onmousemove="$(this).css(\'background\-color\',\'#FFCCFF\')" onmouseout="$(this).css(\'background\-color\',\'\')"><td center="left" onclick="$(\'#'.$_POST["div"].'\').hide();">关闭</td></tr>';
        
		while($records = mysql_fetch_array($query, MYSQL_ASSOC))
	    {
	    	$records["emp_firstname2"] = str_replace($EmpName,'<font color=red>'.$EmpName.'</font>',$records["emp_firstname"]);
	    	$str .= '<tr style="cursor:default" onmousemove="$(this).css(\'background\-color\',\'#FFCCFF\')" onmouseout="$(this).css(\'background\-color\',\'\')"><td center="left" onclick="showproname(\''.$records["emp_firstname"].'\',\''.$records["emp_number"].'\',\''.$EmpIdId.'\',\''.$EmpNameId.'\',\''.$div.'\');">'.$records["emp_firstname2"].'</td></tr>';
	    }
	    if ($str != "")
	    {
	    	echo $str;
	    }
	    else {
	    	echo "no";
	    }
	    exit;
	}
	
	/**
	 *查看考勤月度表 
	 **/
	public function ShowAttendanceReport($type="Month",$UserId='') {
		$sysConst = new sysConf();
		$ReportTitleArr =  array('Month'=>'月度考勤','Quarter'=>'季度考勤','Year'=>'年度考勤');
		$ReportId =  array('Month'=>0,'Quarter'=>1,'Year'=>2);
		$where = "Where 1=1 ";
		if($UserId > 0) {
			$where .= " and a.EmpId = {$UserId} ";
		}
		if(intval($_REQUEST['Year']) > 0 && intval($_REQUEST['Month']) > 0) {
			$GetYear = intval($_REQUEST['Year']);
			$GetMonth = intval($_REQUEST['Month']);
		} else {
			$GetYear = @date("Y");
			$GetMonth = intval(@date("m"));
		}
		$DateStr = $GetYear."-".$GetMonth;
        $limit = "";
        $list = array();
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;
            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }
        $sql = "select count(*) as allcount from hs_hr_emp_attendance_stat a ".$where." and a.StatType={$ReportId[$type]} and a.DateStr='{$DateStr}'";
        $query = $this->db->executeQuery($sql);
		$Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
		
        $sql = "select a.*,b.emp_number,b.employee_id,b.emp_firstname,b.work_station from hs_hr_emp_attendance_stat a left join hs_hr_employee b on a.EmpId=b.emp_number ".$where." and a.StatType={$ReportId[$type]} and a.DateStr='{$DateStr}' ".$limit;
        //echo $sql;exit;
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$row['riqi'] = $GetYear."年-".$GetMonth."月";//date("Y-m",$j);
			$row['crtype'] = $ReportId[$type];
			$row['cryear'] = $GetYear;//date("Y",$j);
			$row['crotherd'] = $GetMonth;//date("m",$j);
			if($row['EmpId']) {
				$ReportRow = unserialize($row['Content']);
			} else {
				$ReportRow = "";
			}
			$row = array_merge($row,$ReportRow);
			$list[] = $row;
		}
		//print_r($list);exit;
		
		$records['list'] = $list;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $Allcount['allcount'];
		$records['Title'] = $ReportTitleArr[$type];
		$records['action'] = $type;

		$path = "/templates/salary/ShowAttendanceReport.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	
	public function showSalaryConfig($messageType = null) {

		if (Config::getSalaryEmpChangeTime()) {
			$records['empChangeTime'] = true;
		} else {
			$records['empChangeTime'] = false;
		}

		if (Config::getSalaryEmpEditSubmitted()) {
			$records['empEditSubmitted'] = true;
		} else {
			$records['empEditSubmitted'] = false;
		}

		if (Config::getSalarySupEditSubmitted()) {
			$records['supEditSubmitted'] = true;
		} else {
			$records['supEditSubmitted'] = false;
		}

		$records['messageType'] = $messageType;
		$path = '/templates/time/salaryConfig.php';
		$template = new TemplateMerger($records, $path);
		$template->display();

	}
	
	
	/**
	 *根据员工应缴税的金额 算出他应缴多少税 
	 **/
	function getEmpTax($salary_tax) {
		switch ($salary_tax) {
			case $salary_tax<=1500 :
				$tax = round($salary_tax*0.03,2);
				return $tax_arr = array('tax_rate'=>3,'minus_amount'=>0,'tax'=>$tax);
			case $salary_tax<=4500 :
				$tax = round($salary_tax*0.1,2)-105;
				return $tax_arr = array('tax_rate'=>10,'minus_amount'=>105,'tax'=>$tax);
			case $salary_tax<=9000 :
				$tax = round($salary_tax*0.2,2)-555;
				return $tax_arr = array('tax_rate'=>20,'minus_amount'=>555,'tax'=>$tax);
			case $salary_tax<=35000 :
				$tax = round($salary_tax*0.25,2)-1005;
				return $tax_arr = array('tax_rate'=>25,'minus_amount'=>1005,'tax'=>$tax);
			case $salary_tax<=55000 :
				$tax = round($salary_tax*0.3,2)-2755;
				return $tax_arr = array('tax_rate'=>30,'minus_amount'=>2755,'tax'=>$tax);
			case $salary_tax<=80000 :
				$tax = round($salary_tax*0.35,2)-5505;
				return $tax_arr = array('tax_rate'=>35,'minus_amount'=>5505,'tax'=>$tax);
			case $salary_tax>80000 :
				$tax = round($salary_tax*0.45,2)-13505;
				return $tax_arr = array('tax_rate'=>45,'minus_amount'=>13505,'tax'=>$tax);
		}
	}
	
	/**
	 *月度工资预算 算法 
	 **/
	function CalcuBudgetSalary($year, $month, $where='', $limit='', $isChecked=0) {
		
		require_once ROOT_PATH . '/lib/models/hrfunct/EmpInfo.php';
		$empinfoObj = new EmpInfo();
		require_once ROOT_PATH . '/lib/models/eimadmin/DaySalary.php';
		$daysalObj = new DaySalary();
		require_once ROOT_PATH . '/lib/models/hrfunct/EmpAdminExam.php';
		$empexamObj = new EmpAdminExam();
		require_once ROOT_PATH . '/lib/models/hrfunct/EmpSkillAllowance.php';
		$empskillalwObj = new EmpSkillAllowance();
		require_once ROOT_PATH . '/lib/controllers/AttendanceController.php';
		$AttendanceController = new AttendanceController();
		require_once ROOT_PATH . '/lib/models/hrfunct/EmpBasSalary.php';
		$empBasSalObj = new EmpBasSalary();
		require_once ROOT_PATH . '/lib/models/hrfunct/EmpBasSalary.php';
		$empBasSalObj = new EmpBasSalary();
		require_once ROOT_PATH . '/lib/models/hrfunct/AdministraMana.php';
		$Administra = new AdministraMana();
		
		$salRules = $this->getRuleValue();
		$nightAlw=0;
		if($salRules['hadNightAllowance'] && $salRules['NightAllowance']>0) $nightAlw = $salRules['NightAllowance'];
		//$countsql = "select count(*) from hs_hr_emp_basicsalary;";
		$countsql = "select count(*) from hs_hr_employee;";
		$query = $this->db->executeQuery($countsql);
        $Allcount = mysql_fetch_array($query);
        $Allcount = $Allcount[0];
        $orderby = " order by work_station desc, emp_number asc";
        
		//$basicsql = "select * from hs_hr_emp_basicsalary {$where} {$limit}";
		$basicsql = "select emp_number from hs_hr_employee {$where} {$orderby} {$limit}";
		$query = $this->db->executeQuery($basicsql);
		$i=0;
		$inssql='';
		$list = array();
		while ($emp_row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$emp_number = $emp_row['emp_number'];
			$row = $empBasSalInfo = $empBasSalObj->filterEmpBasSal($emp_number);
			$row['emp_number'] = $emp_number;
			
			$basicinfo = $empinfoObj->filterEmpMain($emp_number);
			$row['emp_name'] = $basicinfo[0][2]; //the first name
			$jobinfo = $empinfoObj->filterEmpJobInfo($emp_number);
			$row['join_date'] = $jobinfo[0][5]?$jobinfo[0][5]:"2000-00-00";
			$row['job'] = $jobinfo[0][9];
			$row['department'] = $jobinfo[0][4];
			$row['manager_date'] = $row['EFFECTIVE_DATE']?$row['EFFECTIVE_DATE']:"2000-00-00";
			
			$serverYears = round((time()-strtotime($row['join_date']))/31536000,2);
			switch ($serverYears) {
				//case $serverYears>10.0849:
				case $serverYears>=10:
					$row['niangong'] = 200;
					break;
				//case $serverYears>3.0411:
				case $serverYears>=3:
					$row['niangong'] = 100;
					break;
				//case $serverYears>2.0548:
				case $serverYears>=2:
					$row['niangong'] = 70;
					break;
				default:
					$row['niangong'] = 0;	
			}
			
			//$row['ServerYear'] = round(((time()-strtotime($row['join_date']))/31536000),2); //365*24*3600=31536000
			
			$daysal_id = $row['DAYSAL_ID'];
			if ($daysal_id) {
				$hour_salary = $daysalObj->getDaySalaryById($daysal_id);
			}else {
				$hour_salary = 0;
			}
			$row['hour_salary'] = $hour_salary;
			
			$row['year'] = $year;
			$row['month'] = $month;
			//获取该月份的考勤数据
			$attendReport = $AttendanceController->CheckReportAndGet($emp_number,0,$year,$month);
			if(is_array($attendReport)) {
				$row['A_attendance_hours'] = $attendReport['WorkHours'];
				$row['Y_absence_hours'] = $attendReport['later']+$attendReport['ZaoTui']+$attendReport['kuangGong'];
				$night_days = $attendReport['yeban'];
				$row['C_OT_hours15'] = $attendReport['psjiaban']['time'];
				$row['C_OT_hours2'] = $attendReport['weekjiaban']['time'];
				$row['C_OT_hours3'] = $attendReport['holidayjiaban']['time'];
			}else {
				$row['A_attendance_hours'] = $row['Y_absence_hours'] = $night_days = 0;
				$row['C_OT_hours15'] = $row['C_OT_hours2'] = $row['C_OT_hours3'] = 0;
			}
			$row['A_total'] = round($row['A_attendance_hours']*$hour_salary,0);
			
			$row['C_OT_salary15'] = round($row['C_OT_hours15']*$hour_salary*1.5,2);
			$row['C_OT_salary2'] = round($row['C_OT_hours2']*$hour_salary*2,2);
			$row['C_OT_salary3'] = round($row['C_OT_hours3']*$hour_salary*3,2);
			$row['C_total'] = round(($row['C_OT_salary15']+$row['C_OT_salary2']+$row['C_OT_salary3']));
			
			
			$examArr = $empexamObj->filterEmpAdminExam2($emp_number);
			$adm_pay = 0;
			if(is_array($examArr) && count($examArr)>0) {
				//print_r($examArr);exit;
				foreach ($examArr as $exam) {
					$adm_pay += $exam[1]; //管理考课加薪总和
				}
			}
			$row['B_education'] = $row['EDU_PAY']?$row['EDU_PAY']:0;
			$row['B_manager'] = $adm_pay;
			$row['B_job'] = $row['JOB_PAY']?$row['JOB_PAY']:0;
			
			$skillalwArr = $empskillalwObj->filterEmpSkillAlw2($emp_number);
			$row['B_skill_alw']=0;
			foreach ($skillalwArr as $skillalw) {
				$row['B_skill_alw'] += $skillalw[1];
			}
			$row['B_skill_alw'] += $row['OTHER_ALLOWANCE'] + $row['HIGHT_TEMP_ALLOWANCE'];//还要加上其他的一些津贴
			$row['B_award'] = 0; //评估奖金
			$bonuspenalties = $Administra->getOneBonuspenalties($year,$month,$emp_number);
			if(is_array($bonuspenalties)) {
				foreach($bonuspenalties as $b) {
					$row['B_award'] += $b['BonusPenaltyMoney'];
				}
			}
			$row['B_total'] = round(($row['EDU_PAY']+$adm_pay+$row['JOB_PAY']),2)+$row['B_skill_alw']+$row['niangong']+$row['B_award'];
			
			$row['night_snack_fee'] = round($nightAlw*$night_days); //夜餐合计费用
			$row['D_award'] = 0; //奖励
			$row['D_other'] = 0;
			$row['D_total'] = round($row['night_snack_fee']+$row['D_award']+$row['D_other']);
			
			$row['PI_salary'] = round(($row['A_total']+$row['B_total']+$row['C_total']+$row['D_total']),2);
			$row['Y_other'] = round($row['Y_absence_hours']*$hour_salary);
			$row['Y_total'] = round(($row['LOSEWORK_INSURANCE']+$row['MEDICAL_INSURANCE']+$row['ENDOWMENT_INSURANCE']+$row['MATERNITY_INSURANCE']+$row['HOUSING_FUND']+$row['Y_other']),2);
			$row['TB_salary'] = round(($row['PI_salary']-$row['Y_total']),2);
			$row['M_total'] = $salRules['zero_bracket_amount'] ? intval($salRules['zero_bracket_amount']) : 0;
			$row['T_total'] = $row['TB_salary']-$row['M_total'];
			if($row['T_total']<0){
				$row['T_total']=0;
				$row['tax_rate']=$row['minus_amount']=$row['tax']=0;
			}else {
				$tax_arr = $this->getEmpTax($row['T_total']);
				$row['tax_rate'] = $tax_arr['tax_rate'];
				$row['minus_amount'] = $tax_arr['minus_amount'];
				$row['tax'] = $tax_arr['tax'];
			}
			$row['actual_sarlary'] = round(($row['TB_salary']-$row['tax']));
			
			$list[$i] = $row;
			$i++;
			
			if($isChecked) {
				$inssql = "insert into hs_hr_salary_budget(department,emp_number,emp_name,join_date,manager_date,year,month,niangong,B_education,B_manager,B_job,A_total,B_award,B_skill_alw,B_total,hour_salary,A_attendance_hours,C_OT_hours15,C_OT_hours2,C_OT_hours3,C_OT_salary15,C_OT_salary2,C_OT_salary3,C_total,night_snack_fee,D_award,D_other,D_total,PI_salary,Y_absence_hours,Y_other,Y_total,TB_salary,M_total,T_total,tax_rate,minus_amount,tax,actual_sarlary) values('{$row['department']}','{$emp_number}','{$row['emp_name']}','{$row['join_date']}','{$row['manager_date']}','{$year}','{$month}','{$row['niangong']}','{$row['B_education']}','{$row['B_manager']}','{$row['B_job']}','{$row['A_total']}','{$row['B_award']}','{$row['B_skill_alw']}','{$row['B_total']}','{$row['hour_salary']}','{$row['A_attendance_hours']}','{$row['C_OT_hours15']}','{$row['C_OT_hours2']}','{$row['C_OT_hours3']}','{$row['C_OT_salary15']}','{$row['C_OT_salary2']}','{$row['C_OT_salary3']}','{$row['C_total']}','{$row['night_snack_fee']}','{$row['D_award']}','{$row['D_other']}','{$row['D_total']}','{$row['PI_salary']}','{$row['Y_absence_hours']}','{$row['Y_other']}','{$row['Y_total']}','{$row['TB_salary']}','{$row['M_total']}','{$row['T_total']}','{$row['tax_rate']}','{$row['minus_amount']}','{$row['tax']}','{$row['actual_sarlary']}');";
				$this->db->executeQuery($inssql);
			}
		}
		//echo $inssql;exit;
		if ($inssql) {
			$checker = $_SESSION['fname'];
			$check_date = @date("Y-m-d");
			$ischksql = "insert into hs_hr_check_salary_budget(ck_year,ck_month,checker,check_date) values($year,$month,'{$checker}','{$check_date}');";
			//echo $ischksql;exit;
			$this->db->executeQuery($ischksql);
		}
		$result['list'] = $list;
		$result['count'] = $Allcount;
		return $result;
	}
	
	/**
	 *月度工资预算表 
	 **/
	public function ShowBudgetSalary($year, $month, $UserId='') {
		$sysConst = new sysConf();
		$where = "Where 1=1 ";
		if($UserId > 0) {
			$where .= " and emp_number = {$UserId} ";
		}
		$where_cal = $where;
		if (!$year) {
			$year = @date("Y",time());
		}
		if (!$month) {
			$month = intval(@date("m",time()));
		}
		$where .= $this->GetSearchSlqWhere($year, $month);
		$where_cal .= $this->GetSearchSlqWhere($year, $month, '', '', $type='CalSalary');
		//$orderby = " order by department asc, emp_number asc";
		$orderby = " order by hour_salary asc, emp_number asc";
        $limit = "";
        $list = array();
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= $sysConst->itemsPerPage;

            $limit = " limit {$pageNO}, {$sysConst->itemsPerPage}";
        }
        
        $sql = "select count(*) as allcount from hs_hr_salary_budget {$where}";
        $query = $this->db->executeQuery($sql);
        $Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
        $Allcount = $Allcount['allcount'];
        if ($Allcount>0) {
        	$sql = "select * from hs_hr_salary_budget {$where} {$orderby} {$limit}";
        	$query = $this->db->executeQuery($sql);
        	while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
        		$list[] = $row;
        	}
        	
        }else {
        	$result = $this->CalcuBudgetSalary($year, $month, $where_cal, $limit, 0);
        	$list = $result['list'];
        	$Allcount = $result['count'];
        }
		
		$records['list'] = $list;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $Allcount;
		//print_r($list);exit;

		$path = "/templates/salary/ShowBudgetSalary.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	/**
	 *月度工资预算表审核 
	 **/
	function ExamBudgetSalary() {
		$year = intval($_POST['year']);
		$month = intval($_POST['month']);
		$where = "where ck_year='{$year}' and ck_month='{$month}'";
		$sql = "select count(*) as num from hs_hr_check_salary_budget {$where}";
        $query = $this->db->executeQuery($sql);
		$Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
        $num = $Allcount['num'];
        
        if($num>0) {
        	$this->redirect ("该月的工资预算报表已审核,无须重复审核了!", "?salcode=budget");
        	exit;
        }else {
        	$this->CalcuBudgetSalary($year,$month,'','',1);
        }
		
		$this->redirect ("审核成功", "?salcode=budget");
		exit;
	}
	
	/**
	 *月度工资条 
	 **/
	public function ShowSalaryPaper($year, $month, $UserId='') {
		//$sysConst = new sysConf();
		//$ReportTitleArr =  array('Month'=>'月度工资条','Quarter'=>'季度工资条','Year'=>'年度工资条');
		//$ReportId =  array('Month'=>0,'Quarter'=>1,'Year'=>2);
		$where = "Where 1=1 ";
		if($UserId > 0) {
			$where .= " and emp_number = {$UserId} ";
		}
		if (!$year) {
			$year = @date("Y",time());
		}
		if (!$month) {
			$month = intval(@date("m",time()));
		}
		$where .= $this->GetSearchSlqWhere($year, $month);
        $limit = "limit 0, 10";
        $list = array();
		$pageNO = isset($_POST['pageNO'])?intval($_POST['pageNO']):1;
        if ($pageNO > 0) {
            $pageNO--;
            $pageNO *= 10;
            $limit = " limit {$pageNO}, 10";
        }
        
		$sql = "select count(*) as allcount from hs_hr_salary_budget {$where}";
		$query = $this->db->executeQuery($sql);
		$Allcount = mysql_fetch_array($query, MYSQL_ASSOC);
		
		$sql = "select * from hs_hr_salary_budget {$where} {$limit}";
		
		$query = $this->db->executeQuery($sql);
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			$empid = $row['emp_number'];
			$basicsql = "select adm_exam_salary,tec_allowance,hight_temp_allowance,night_work_allowance,other_allowance,losework_insurance,medical_insurance,endowment_insurance,maternity_insurance,housing_fund from hs_hr_salary_basic where emp_number='{$empid}' and year='{$year}' and month='{$month}' limit 1";
			$query2 = $this->db->executeQuery($basicsql);
			while($row2 = mysql_fetch_array($query2, MYSQL_ASSOC)){
				$row = array_merge($row,$row2);
			}
			$list[] = $row;
		}
		/*echo "<pre>";
		print_r($list);
		echo "</pre>";exit;*/
		$records['list'] = $list;
		$records['pageNo'] = $pageNO;
		$records['Allcount'] = $Allcount['allcount'];
		$records['Title'] = $ReportTitleArr[$type];
		$records['action'] = $type;

		$path = "/templates/salary/ShowSalaryPaper.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}

	public function redirect($message=null, $url = null) {

		if (isset($url)) {
			$mes = "";
			if (isset($message)) {
				$mes = "&message=";
			}
			$url=array($url.$mes);
			$id="";
		} else if (isset($message)) {
			preg_replace('/[&|?]+id=[A-Za-z0-9]*/', "", $_SERVER['HTTP_REFERER']);

			if (preg_match('/&/', $_SERVER['HTTP_REFERER']) > 0) {
				$message = "&message=".$message;
				$url = preg_split('/(&||\?)message=[A-Za-z0-9]*/', $_SERVER['HTTP_REFERER']);
			} else {
				$message = "?message=".$message;
			}

			if (isset($_REQUEST['id']) && !empty($_REQUEST['id']) && !is_array($_REQUEST['id'])) {
				$id = "&id=".$_REQUEST['id'];
			} else {
				$id="";
			}
		} else {
			if (isset($_REQUEST['id']) && !empty($_REQUEST['id']) && (preg_match('/&/', $_SERVER['HTTP_REFERER']) > 0)) {
				$id = "&id=".$_REQUEST['id'];
			} else if (preg_match('/&/', $_SERVER['HTTP_REFERER']) == 0){
				$id = "?id=".$_REQUEST['id'];
			} else {
				$id="";
			}
		}

		header("Location: ".$url[0].$message.$id);
	}
	
	/**
	 *奖罚、调薪历史记录 
	 **/
	function DoOfficRecords($getArr,$postArr) {
		$form_creator = new FormCreator($getArr,$postArr);
		if(isset($getArr['salcode'])) $DoAction = $getArr['salcode']."Do";
		$form_creator ->formPath = '/templates/salary/'.$getArr['salcode'].'.php';
		$Administra = new AdministraMana();
		$action = "";
		if($getArr['action'] == "addmode" || $getArr['capturemode'] == "addmode") {
			$action = "addmode";
		} elseif($getArr['action'] == "updatemode" || $getArr['capturemode'] == "updatemode") {
			$action = "updatemode";
		} elseif($getArr['action'] == "DeleteMode" || $postArr['delState'] == "DeleteMode") {
			$action = "DeleteMode";
		}
		if(method_exists($Administra,$DoAction)) {
			$ruselt = $Administra->$DoAction($action,$getArr,$postArr);
		} else {
			//$ruselt = $Administra->addEmpAdministraMana();
			$ruselt = array();
		}
		 
		if (isset($postArr['pageNO'])) {
			$currentPage = (int) $postArr['pageNO'];
		} elseif (isset($getArr['pageNO'])) {
			$currentPage = (int) $getArr['pageNO'];
		} else {
			$currentPage = 1;
		}
		if($action == "addmode") {
			$form_creator->popArr = $ruselt;
		} else {
			$form_creator->popArr['currentPage'] = $currentPage;
			$form_creator->popArr['emplist'] = $ruselt['list'];		
			$form_creator->popArr['temp'] = $ruselt['count']['allcount'];
		}
		$form_creator->display();
	}
}
?>
